package geektime.spring.springbucks.service;

import geektime.spring.springbucks.mapper.CoffeeMapper;
import geektime.spring.springbucks.model.Coffee;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

import static javax.transaction.Transactional.TxType.NOT_SUPPORTED;
import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.exact;

@Slf4j
@Service
@Transactional
@CacheConfig(cacheNames = "coffee")
public class CoffeeService {

    @Autowired
    private CoffeeMapper coffeeMapper;

    @Cacheable
    @Transactional(NOT_SUPPORTED)
    public Coffee findOneCoffee(String name) {
        Coffee coffee = coffeeMapper.findOne(name);
        log.info("Coffee Found: {}", coffee);
        return coffee;
    }

    @Cacheable
    @Transactional(NOT_SUPPORTED)
    public List<Coffee> findAll() {
        return coffeeMapper.findAll();
    }

    @Cacheable
    @Transactional(NOT_SUPPORTED)
    public Coffee findById(Long id) {
        return coffeeMapper.findById(id);
    }

    @CacheEvict(allEntries = true)
    public void delete(Long id) {
        coffeeMapper.delete(id);
    }

    @CacheEvict(allEntries = true)
    public void update (Coffee coffee) {
        coffeeMapper.update(coffee);
    }

    @CacheEvict(allEntries = true)
    public void reloadCoffee() {
    }

    @Transactional(NOT_SUPPORTED)
    public List<Coffee> findAllWithRowBounds(RowBounds rowBounds) {
        return coffeeMapper.findAllWithRowBounds(rowBounds);
    }

    @Transactional(NOT_SUPPORTED)
    public List<Coffee> findAllWithParam(int pageNum, int pageSize) {
        return coffeeMapper.findAllWithParam(pageNum, pageSize);
    }
}
